package a.client.lib_common.utils

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
@author:jacky
@Date:2021/1/25
 百度翻译MD5加密
 **/
object MD5 {
    fun encode(password: String): String {
        try {
            val instance: MessageDigest = MessageDigest.getInstance("MD5")  // 获取md5加密对象
            // 对字符串加密，返回字节数组
            val digest: ByteArray =
                instance.digest(password.toByteArray())
            val sb = StringBuffer()
            for (b in digest) {
                // 获取低八位有效值
                val i: Int = b.toInt() and 0xff
                // 将整数转化为16进制
                var hexString = Integer.toHexString(i)
                if (hexString.length < 2) {
                    // 如果是一位的话，补0
                    hexString = "0$hexString"
                }
                sb.append(hexString)
            }
            return sb.toString()

        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return ""
    }
}